package com.lanyou.cook.paramsetting;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.lanyou.cook.entity.domain.ParamSetting;
import com.lanyou.cook.util.gson.GsonUtil;

@Service
public class ParamSettingService {

	@Autowired
	private ParamSettingReppository paramSettingReppository;
	
	public JsonElement getAsJson(String paramName){
		ParamSetting entity = paramSettingReppository.findByParamName(paramName);
		if(entity != null){
			return GsonUtil.getDefaultJsonParser().parse(entity.getParamValue());
		} else {
			return JsonNull.INSTANCE;
		}
	}
	
	public <T> T getAsObject(String paramName, Class<T> clazz){
		JsonElement je = getAsJson(paramName);
		if(je.isJsonObject()){
			return GsonUtil.getDefaultGson().fromJson(je, clazz);
		} else {
			return null;
		}
	}
	
	public void saveJson(String paramName, JsonElement je){
		ParamSetting entity = paramSettingReppository.findByParamName(paramName);
		if(entity == null){
			entity = new ParamSetting();
			entity.setParamName(paramName);
		}
		entity.setParamValue(je.toString());
		
		paramSettingReppository.save(Arrays.asList(entity));
	}
	
	public void saveObject(String paramName, Object o){
		ParamSetting entity = paramSettingReppository.findByParamName(paramName);
		if(entity == null){
			entity = new ParamSetting();
			entity.setParamName(paramName);
		}
		entity.setParamValue(GsonUtil.getDefaultGson().toJson(o));
		
		paramSettingReppository.save(Arrays.asList(entity));
	}
	
}
